package com.zhiwang.planet.widget

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.content.Context
import android.text.TextUtils
import android.util.AttributeSet
import android.widget.TextView
import androidx.appcompat.widget.AppCompatTextView

class ExpandableTextView(context: Context, attrs: AttributeSet?) : AppCompatTextView(context, attrs) {

    private var normalLineCount = -1
    private var animating = false
    private var expand = false


    override fun setText(text: CharSequence, type: TextView.BufferType) {

        if (!TextUtils.equals(text, getText())) {
            viewTreeObserver.addOnPreDrawListener {
                if (normalLineCount == -1) {
                    normalLineCount = lineCount
                    if (normalLineCount > 0) {
                        maxLines = 0
                        maxEms = 13
                        ellipsize = TextUtils.TruncateAt.END
                    }
                }
                true
            }
        }
        super.setText(text, type)

    }

    fun collapse() {
        if (lineCount == 0)
            return
        else maxLines = 0
    }

    fun expand() {
        if (lineCount == normalLineCount)
            return
        else maxLines = normalLineCount
    }


    fun toggle(animation: Boolean) {

        if (animating)
            return

        var start = 0
        var end = normalLineCount

        if (expand) {
            start = normalLineCount
            end = 0
        }

        if (animation.not()) {
            maxLines = normalLineCount
            return
        }


        //need animation
        val animator = ValueAnimator.ofInt(start, end).setDuration(250)
        val finalEnd = end
        animator.addUpdateListener { animation ->
            val lineCount = animation.animatedValue as Int
            maxLines = lineCount
            animating = finalEnd != lineCount
            if (!animating)
                expand = !expand
        }
        animator.addListener(object : AnimatorListenerAdapter() {

            override fun onAnimationStart(animation: Animator) {
                super.onAnimationStart(animation)
                animating = true

            }

            override fun onAnimationEnd(animation: Animator) {
                super.onAnimationEnd(animation)
                animating = false
            }
        })

        animator.start()
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        if (expand.not()) {
            maxLines = 0
        } else if (normalLineCount != -1)
            maxLines = normalLineCount
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        expand = false
    }

}
